package models

import (
	"time"
	"gorm.io/gorm"
)

// VersionInfo 版本信息模型
type VersionInfo struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	Version   string    `gorm:"type:varchar(50);not null" json:"version"`
	Platform  string    `gorm:"type:varchar(50);not null" json:"platform"`
	UserID    string    `gorm:"type:varchar(50);not null" json:"userId"`
	Timestamp time.Time `gorm:"not null" json:"timestamp"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

// BeforeCreate 在创建前设置时间戳
func (v *VersionInfo) BeforeCreate(tx *gorm.DB) error {
	v.CreatedAt = time.Now()
	v.UpdatedAt = time.Now()
	return nil
}

// BeforeUpdate 在更新前设置时间戳
func (v *VersionInfo) BeforeUpdate(tx *gorm.DB) error {
	v.UpdatedAt = time.Now()
	return nil
}

// SaveVersionInfo 保存版本信息
func SaveVersionInfo(versionInfo VersionInfo) error {
	db := GetDB()
	return db.Create(&versionInfo).Error
}

// GetLatestVersionInfo 获取最新版本信息
func GetLatestVersionInfo(platform string) (VersionInfo, error) {
	var versionInfo VersionInfo
	db := GetDB()
	result := db.Where("platform = ?", platform).Order("created_at DESC").First(&versionInfo)
	return versionInfo, result.Error
}